import { queryWithdraw } from '@/services/person';
import { queryBuyCurrent, queryBuyFixed, queryRefundCurrent } from '@/services/product';
import { BEP_ABI } from '@/web3/contract/bep20';
import { WALLETABI } from '@/web3/contract/WalletCenter';
import { Box, Flex, Text } from '@chakra-ui/react';
import { Button, Input, message, Modal, Spin } from 'antd';
import React, { useState, useEffect } from 'react';
import { connect, useDispatch } from 'react-redux';
import { useAccount, useContractRead, useContractWrite, usePrepareContractWrite, useSignMessage } from 'wagmi';
import { useTranslation } from 'react-i18next';
import { contactFunctionCall } from '@/utils/web3';

import Web3 from 'web3';
import { ethers } from 'ethers'
import { toMillimeter } from '@/utils/utils';



type ModelType = string | 'fixed' | 'current' | 'redeem' | 'Recharge' | 'extract' | 'limit';

type Props = {
  type: ModelType; //弹窗类型： 定期，活期，购买额度，赎回本金，充值，提币
  // blance: string; //  可用额度 如USDT
  data: { ProductInfo?: PruductInfo; investTotal?: number; ordersId?: number; walletInfo?: WalletInfo } // 弹窗用到的数据
  isShowModal: (flag: boolean, reload: boolean) => void; // 弹窗的回调
  inAccount?: string; // 理财余额
};

const ModelType = {
  FIXED: 'fixed', // 定期
  CURRENT: 'current', //活期
  LIMIT: 'limit', // 购买额度
  REDEEM: 'redeem', // 赎回
  RECHAEGE: 'Recharge', // 充值
  EXTRACT: 'extract', //提币
};

const MyModal = (props: Props) => {
  const { type, data, isShowModal, inAccount } = props;
  const [open, setOpen] = useState(true);
  const [loading, setLoading] = useState(false)
  const [inputVal, setInputVal] = useState('')
  const [usdtBalance, setUsdtBalance] = useState('')
  const [bndBalance, setBNDtBalance] = useState('')
  const [currentUSDT, setCurrentUSDT] = useState('')
  const [currentBND, setCurrentBND] = useState('')
  const [currentLimitBND, setCurrentLimitBND] = useState('') // 购买额度的‘需支付’
  const [withdrawInfo, setWithDrawInfo] = useState({} as Withdraw) // 提币参数
  const [realIpt, setRealIpt] = useState('') // 提币-实际到账金额
  const [isGetInfo, setIsGetInfo] = useState(false) //确保withdrawInfo有值

  const [LimitNum, setLimitNum] = useState('') // 处理数据
  const [rechargeNum, setRechargeNum] = useState('') // 处理数据
  const [linkBalance, setLinkBalance] = useState('') // 链上余额
  const [linkLimit, setLinkLimit] = useState('') // 链上授权额度
  const dispatch = useDispatch()

  const { t } = useTranslation();


  const walletList = data?.ProductInfo?.walletList
  const fixedOrderInfo = data?.ProductInfo?.fixedOrderInfo
  const bndPrice = data?.ProductInfo?.bndPrice
  const investTotal = data.investTotal
  const ordersId = data.ordersId
  const signMsg = data.ProductInfo?.message
  const walletInfo = data.walletInfo

  // 获取地址
  const { address }: Account = useAccount();
  // 获取签名
  const { data: signatures, signMessageAsync } = useSignMessage({
    message: signMsg || walletInfo && walletInfo.message,
  })

  // 获取额度和充值
  const contactFunctionSend = (abi: any, method: any, params: any, contract: any, account: any, value: any, cb: any,) => {
    const web3 = (window.ethereum && new Web3(window.ethereum)) || null;
    let iface = new ethers.utils.Interface([abi])
    let encodeData = iface.encodeFunctionData(method, params)

    let tx = {
      from: account,
      to: contract,
      value: value,
      data: encodeData
    }
    web3.eth.estimateGas(tx, (gasError: any, gasResult: any) => {
      if (gasError) {
        let err = JSON.parse(gasError.message.substr(gasError.message.indexOf("{")))
        // alert(err.message.substr(err.message.indexOf(":") + 2))
        cb(err, null)
        message.error(err.message.substr(err.message.indexOf(":") + 2));
        setLoading(false);
        return
      }
      //方法2，sync
      web3.eth.sendTransaction(tx)
        .then((receipt: any) => {
          cb({}, receipt)
        }).catch((err: any) => {
          message.error(err.message.substr(err.message.indexOf(":") + 2));
          setLoading(false);
        })

    });
  }



  // 关闭弹窗
  const hideModal = (reload?: boolean) => {
    setOpen(false);
    isShowModal && isShowModal(false, reload || false);
  };

  //提交按钮
  const confirmBtn = async () => {
    setLoading(true);
    if (type === ModelType.RECHAEGE) {

      // 判断充值的金额和链上额度，如果链上额度不够，调用授权
      if (Number(linkLimit) < Number(inputVal)) {
        contactFunctionSend('function approve(address spender, uint256 amount) external returns (bool)',
          'approve',
          [walletInfo?.businessContractAddress, LimitNum],
          walletInfo && walletInfo.coinContractAddress,
          address,
          0,
          () => {
            contactFunctionSend('function recharge(address token, uint256 value) external returns (bool)',
              'recharge',
              [walletInfo?.coinContractAddress, rechargeNum],
              walletInfo && walletInfo.businessContractAddress,
              address,
              0,
              (err: any) => {
                message.success('success');
                hideModal(true);
                setLoading(false);
              }
            )
          }
        )
        return
      }
      // 充值额度小于链上额度，调用充值
      if (Number(linkBalance) > Number(inputVal)) {
        contactFunctionSend('function recharge(address spender, uint256 amount) external returns (bool)',
          'recharge',
          [walletInfo?.coinContractAddress, rechargeNum],
          walletInfo && walletInfo.businessContractAddress,
          address,
          0,
          () => {
            message.success('success');
            hideModal(true);
            setLoading(false);
          }
        )
      }
    } else {
      //获取签名
      signMessageAsync().then(res => {
        if (res) {
          if (type === ModelType.FIXED || type === ModelType.LIMIT) {
            // 购买定期的接口
            queryBuyFixed({ amount: inputVal, signature: res, type: type === ModelType.FIXED ? 1 : 2, address }).then(res => {
              if (res.code === 0) {
                message.success('success')
                setLoading(false);
                hideModal(true);
              } else {
                message.error(res.msg)
                setLoading(false);
              }
            })
          }
          // 购买活期
          if (type === ModelType.CURRENT) {
            queryBuyCurrent({ amount: inputVal, signature: res, address }).then(res => {
              if (res.code === 0) {
                message.success('success')
                setLoading(false);
                hideModal(true);
              } else {
                message.error(res.msg)
                setLoading(false);
              }
            })
          }
          // 赎回本金
          if (type === ModelType.REDEEM) {
            queryRefundCurrent({ id: ordersId, signature: res, address }).then(res => {
              if (res.code === 0) {
                message.success('success')
                setLoading(false);
                hideModal(true);
              } else {
                message.error(res.msg)
                setLoading(false);
              }
            })
          }
          // 提币
          if (type === ModelType.EXTRACT) {
            queryWithdraw({ walletId: walletInfo?.id, amount: inputVal, signature: res, address }).then(res => {
              if (res.code === 0) {
                message.success('success')
                setLoading(false);
                hideModal(true);
              } else {
                message.error(res.msg)
                setLoading(false);
              }
              // setWithDrawInfo(data)
              // setIsGetInfo(true)
            })
          }
        }
      })
    }
  };

  // 查询余额和额度
  useEffect(() => {
    if (type === ModelType.RECHAEGE && address) {
      const web3 = (window.ethereum && new Web3(window.ethereum)) || null;
      // 查询余额
      contactFunctionCall("function balanceOf(address account) view external returns(uint256)",
        "balanceOf",
        [address],
        walletInfo && walletInfo.coinContractAddress,
        (error: any, result: any) => {
          const linkbnd = web3.utils.fromWei(result[0].toString(), "ether")
          const newBnd = Number(linkbnd).toFixed(2)
          setLinkBalance(newBnd)
        }
      )

      // 查额度
      contactFunctionCall('function allowance(address owner, address spender) external view returns (uint256)',
        "allowance",
        [address, walletInfo?.businessContractAddress],
        walletInfo && walletInfo.coinContractAddress,
        (error: any, result: any) => {
          const linkbnd = web3.utils.fromWei(result[0].toString(), "ether");
          setLinkLimit(linkbnd)
        })
    }
  }, [type, address])

  // 处理金额
  useEffect(() => {
    if (inputVal) {
      const web3 = (window.ethereum && new Web3(window.ethereum)) || null;
      const limitNUm = parseFloat(inputVal) * 100
      // const 
      const toLimit = web3.utils.toWei(limitNUm.toString(), "ether")
      const toRecharge = web3.utils.toWei(inputVal, "ether")
      setRechargeNum(toRecharge)
      setLimitNum(toLimit)
    }
  }, [inputVal])

  // 余额赋值
  useEffect(() => {
    walletList?.map(item => {
      if (item.coin === 'USDT') setUsdtBalance(item.balance)
      if (item.coin === 'BND') setBNDtBalance(item.balance)
    })
  }, [walletList])

  // 计算所需余额
  useEffect(() => {
    if (fixedOrderInfo) {
      const usdt = (parseFloat(inputVal) * fixedOrderInfo.usdtRate).toFixed(2)
      const bnd = ((parseFloat(inputVal) * (1 - fixedOrderInfo.usdtRate)) / Number(bndPrice)).toFixed(2)
      const limitbnd = (parseFloat(inputVal) / Number(bndPrice)).toFixed(2)
      setCurrentBND(bnd)
      setCurrentLimitBND(limitbnd)
      setCurrentUSDT(usdt)
    }
    if (type === ModelType.EXTRACT && walletInfo?.feeRate) {
      if (inputVal) {
        const realBND = (parseFloat(inputVal) * (1 - walletInfo.feeRate)).toFixed(2)
        setRealIpt(realBND)
      } else {
        setRealIpt('0.00')
      }

    }
  }, [inputVal, bndPrice, type])


  return (
    <Box>
      <Modal
        title={
          <Box fontSize={18}>
            {type === ModelType.FIXED
              ? t('modal.Buy_time_deposit')
              : type === ModelType.CURRENT
                ? t('modal.Buy_demand_deposit')
                : type === ModelType.LIMIT
                  ? t('modal.Purchase_income_amount')
                  : type === ModelType.RECHAEGE
                    ? t('modal.Recharge')
                    : type === ModelType.REDEEM
                      ? t('modal.Withdraw_principal')
                      : t('modal.Withdraw')}
          </Box>
        }
        footer={null}
        onCancel={() => hideModal()}
        open={open}
      >
        <Spin spinning={loading} >
          <Flex direction={'column'}>
            {/* 赎回不需要输入框 */}
            {type !== ModelType.REDEEM && (
              <Flex direction={'column'} w={'100%'}>
                <Input
                  style={{ height: '50px', paddingLeft: '17px', backgroundColor: '#DEF0FB', border: '0px', borderRadius: '4px', margin: '15px 0', fontSize: '16px', fontWeight: '600' }}
                  placeholder={type === ModelType.RECHAEGE
                    ? t('modal.Enter_the_amount_2') || ''
                    : type === ModelType.EXTRACT
                      ? t('modal.Enter_the_amount_3') || ''
                      : t('modal.Enter_the_amount') || ''}
                  type={'number'}
                  value={inputVal}
                  onChange={(val) => {
                    setInputVal(val.target.value)
                  }}
                  prefix={(type === ModelType.EXTRACT || type === ModelType.RECHAEGE) ? "" : "$"}
                  suffix={(type === ModelType.EXTRACT || type === ModelType.RECHAEGE) ? (<Box fontWeight={600}>{walletInfo?.coin}</Box>) : ''}

                />
                <Box>
                  {/* 定期理财 */}
                  {type === ModelType.FIXED && (
                    <Box>
                      <Flex justify={'space-between'}>
                        <Text m={0} fontSize={12} lineHeight={'18px'}>
                          {t('modal.Need_to_pay')}
                        </Text>
                        <Text m={0} fontSize={12} lineHeight={'18px'} color="#375BE2">{t('modal.Amount')}</Text>
                      </Flex>
                      <Flex justify={'space-between'}>
                        <Text m={'8px 0'} fontSize={12} lineHeight={'18px'}>

                          {!inputVal ? 0.00 : toMillimeter(currentUSDT)} USDT
                        </Text>
                        <Text m={'8px 0'} fontSize={12} lineHeight={'18px'} color="#375BE2">
                          {toMillimeter(usdtBalance)} USDT
                        </Text>
                      </Flex>
                      <Flex justify={'space-between'} >
                        <Text m={0} fontSize={12} lineHeight={'18px'}>
                          {!inputVal ? 0.00 : toMillimeter(currentBND)} BND
                        </Text>
                        <Text m={'8px 0'} fontSize={12} lineHeight={'18px'} color="#375BE2">
                          {toMillimeter(bndBalance)} BND
                        </Text>
                      </Flex>
                    </Box>
                  )}
                  {/* 购买额度 */}
                  {type === ModelType.LIMIT && (
                    <Box>
                      <Text m={0} fontSize={12} lineHeight={'18px'}>
                        {t('modal.Need_to_pay')} {!inputVal ? 0.00 : toMillimeter(currentLimitBND)} BND
                      </Text>
                      <Text m={0} mt={8} color={'#375BE2'} fontSize={12} lineHeight={'18px'}>
                        {t('modal.Amount')} {toMillimeter(bndBalance)} BND
                      </Text>
                    </Box>
                  )}
                  {/* 提币 */}
                  {type === ModelType.EXTRACT && (
                    <Box>
                      <Flex justify={'space-between'}>
                        <Text m={0} color={'#375BE2'} fontSize={12} lineHeight={'18px'}>
                          {t('modal.Amount')} {toMillimeter(walletInfo?.balance)} {walletInfo?.coin}
                        </Text>
                        <Text m={0} color={'#375BE2'} fontSize={12} lineHeight={'18px'}>
                          {t('modal.handling_fee')} {walletInfo?.feeRate && walletInfo?.feeRate * 100} %
                        </Text>
                      </Flex>

                      <Box fontSize={18} mt={25} fontWeight={600}> {t('modal.Receipt_amount')}</Box>
                      <Input
                        style={{ height: '50px', paddingLeft: '17px', backgroundColor: '#DEF0FB', border: '0px', borderRadius: '4px', margin: '15px 0' }}
                        placeholder=""
                        value={realIpt}
                        disabled
                        suffix={<Box fontWeight={600}>{walletInfo?.coin}</Box>}
                      />
                    </Box>

                  )}
                  {/* 其他 */}
                  {type !== ModelType.LIMIT && type !== ModelType.FIXED && type !== ModelType.EXTRACT && (
                    <Text m={0} color={'#375BE2'} fontSize={12} lineHeight={'18px'}>
                      {type === ModelType.RECHAEGE ? ` ${t('modal.Amount')}: ${toMillimeter(linkBalance)}` : ` ${t('modal.Amount')}: ${toMillimeter(usdtBalance)}`}  USDT
                    </Text>
                  )}
                </Box>
              </Flex>
            )}

            {type === ModelType.REDEEM && (
              <Flex justify={'center'} direction={'column'} align={'center'}>
                <Text m={0} fontSize={12} lineHeight={'18px'}>
                  {t('modal.Available_amount')}
                </Text>
                <Text m={0} mt={10} fontSize={24} lineHeight={'36px'} fontWeight={700}>
                  $ {toMillimeter(investTotal)}
                </Text>
              </Flex>
            )}

            {/* 提交按钮 */}
            <Button
              onClick={confirmBtn}
              style={{
                width: '220px',
                margin: '25px auto 0px',
                height: '40px',
                backgroundColor: type === ModelType.LIMIT || type === ModelType.RECHAEGE || type === ModelType.REDEEM ? '#44CBA2' : '#375BE2',
              }}
              type="primary"
            >
              {(type === ModelType.FIXED || type === ModelType.CURRENT || type === ModelType.LIMIT) && t('button.Confirm_payment')}
              {type === ModelType.RECHAEGE && t('button.Confirmed_3')}
              {type === ModelType.EXTRACT && t('button.Confirmed_4')}
              {type === ModelType.REDEEM && t('button.Confirmed_2')}
            </Button>
          </Flex>

        </Spin>

      </Modal>

    </Box>
  );
};

export default MyModal
